/*************************************************************************
	> File Name: fork_file.c
	> Author: Angel Criss
	> Blog: blog.abbycin.tk 
	> Created Time: Sun 06 Jul 2014 03:33:26 PM CST
 ************************************************************************/

#include<fcntl.h>
#include<sys/stat.h>
#include"head.h"
#include<sys/wait.h>
#include<sys/types.h>

int main(int argc,char *argv[])
{
    char tmp[]="/home/abby/Arch/tmpXXXXXX";
    int fd, flags;
    off_t offset;
    setbuf(stdout,NULL); // disable buffering of stdout
    
    if((fd=mkstemp(tmp))==-1) // creat a temp file
    err("mktemp");
    /*
     * gcc warning: the use of 'mktemp' is dangerous, better use 'mkstemp'
     */

    if(offset=lseek(fd,0,SEEK_CUR)==-1)
        err("(before) lseek");
    printf("(before) Offset: %lld\n",(long long)offset);
    flags=fcntl(fd,F_GETFL); // get the desciptor flags
    printf("(before) O_NONBLOCK: %s\n",(flags & O_NONBLOCK)?"Yes":"NO");

    switch(fork()){
        case -1:
            err("fork");
            break;
        case 0:
            if(lseek(fd,atoi(argv[1]),SEEK_SET)==-1)// reset the offset in child
            err("lseek");

            flags=fcntl(fd,F_GETFL); // fd copy from parent
            flags|=O_NONBLOCK;   // modify the flags
            fcntl(fd,F_SETFL,flags); // set new flags to fd
            break;
        default:
            wait(NULL); // wait child exit and do nothing 
            printf("child finished\n");
            printf("(parent) Offset: %lld\n",(long long)lseek(fd,0,SEEK_CUR));
            flags=fcntl(fd,F_GETFL); // get flags after child modified it
            printf("(parent) O_NONBLOCK: %s\n",(flags & O_NONBLOCK)?"Yes":"NO");
            exit(0);
    }
}

